// Dart imports:
import 'dart:math';

// Flutter imports:
import 'package:flutter/material.dart';

// Package imports:
import 'package:google_fonts/google_fonts.dart';
import 'package:pro_image_editor/pro_image_editor.dart';

// Project imports:
import 'custom_filter_bottombar.dart';
import 'example_helper.dart';

class CustomWidgetsExample extends StatefulWidget {
  final String? filePath;

  const CustomWidgetsExample({super.key, this.filePath});

  @override
  State<CustomWidgetsExample> createState() => _CustomWidgetsExampleState();
}

class _CustomWidgetsExampleState extends State<CustomWidgetsExample>
    with ExampleHelperState<CustomWidgetsExample> {
  late ScrollController _bottomBarScrollCtrl;
  late ScrollController _paintBottomBarScrollCtrl;
  late ScrollController _cropBottomBarScrollCtrl;

  final List<TextStyle> _customTextStyles = [
    GoogleFonts.roboto(),
    GoogleFonts.averiaLibre(),
    GoogleFonts.lato(),
    GoogleFonts.comicNeue(),
    GoogleFonts.actor(),
    GoogleFonts.odorMeanChey(),
    GoogleFonts.nabla(),
  ];

  final _bottomTextStyle = const TextStyle(fontSize: 10.0, color: Colors.white);
  final List<PaintModeBottomBarItem> paintModes = [];

  String? _currentImagePath; // 添加当前图片路径变量
  bool _isSwitching = false; // 标记是否正在切换图片

  @override
  void initState() {
    super.initState();
    _currentImagePath = widget.filePath; // 初始化当前路径
    if (_currentImagePath != null) {
      preCacheImage(filePath: _currentImagePath!);
    }
    _bottomBarScrollCtrl = ScrollController();
    _paintBottomBarScrollCtrl = ScrollController();
    _cropBottomBarScrollCtrl = ScrollController();
  }

  @override
  void dispose() {
    _bottomBarScrollCtrl.dispose();
    _paintBottomBarScrollCtrl.dispose();
    _cropBottomBarScrollCtrl.dispose();
    super.dispose();
  }

  void _switchImage(String newPath) async {
    if (_isSwitching || newPath == _currentImagePath) return;
    // 2. 关闭当前编辑器（如果已打开）
    final editorState = editorKey.currentState;
    if (editorState != null && editorState.canUndo) {
      //提示是否放弃现有更新
    }

    setState(() => _isSwitching = true);

    try {
      // 1. 预缓存新图片
      preCacheImage(filePath: newPath);

      // 3. 更新状态并重建UI
      setState(() {
        _currentImagePath = newPath;
        _isSwitching = false;
      });
    } catch (e) {
      setState(() => _isSwitching = false);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('图片切换失败: ${e.toString()}')));
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!isPreCached) return const PrepareImageWidget();

    return LayoutBuilder(
      builder: (context, constraints) {
        return ProImageEditor.file(
          _currentImagePath,
          // _url,
          key: editorKey,
          callbacks: ProImageEditorCallbacks(
            onImageEditingStarted: onImageEditingStarted,
            onImageEditingComplete: onImageEditingComplete,
            tuneEditorCallbacks: TuneEditorCallbacks(
              onTuneChanged: (value) {
                print("onTuneChanged: $value");
              },
              onTuneFactorChange: (value) {
                print("onTuneFactorChange: $value");
              },
              onTuneFactorChangeEnd: (value) {
                print("onTuneFactorChangeEnd: ${value.first.toMap()}");
              },
            ),
            onCloseEditor: (editorMode) => onCloseEditor(
              editorMode: editorMode,
              enablePop: !isDesktopMode(context),
            ),
            mainEditorCallbacks: MainEditorCallbacks(
              helperLines: HelperLinesCallbacks(onLineHit: vibrateLineHit),
              onInit: () {
                print("onInit");
              },
              onAfterViewInit: () {
                print("onAfterViewInit");
                // final editor = editorKey.currentState;
                // editor?.openCropRotateEditor();
                // rotateStep = 1;
              },
              onOpenSubEditor: (editor) {},
              onUpdateUI: () {},
            ),
            cropRotateEditorCallbacks: CropRotateEditorCallbacks(
              onAfterViewInit: () {
                // final cropState =
                //     editorKey.currentState?.cropRotateEditor.currentState;
                // cropState?.rotate();
              },
              onRotateEnd: (value) {
                // final cropState =
                //     editorKey.currentState?.cropRotateEditor.currentState;
                // cropState?.done();
              },
            ),
          ),
          configs: ProImageEditorConfigs(
            designMode: platformDesignMode,
            mainEditor: MainEditorConfigs(
              enableCloseButton: !isDesktopMode(context),
              widgets: MainEditorWidgets(
                wrapBody: (editor, rebuildStream, content) {
                  print("wrapBody editor: $editor");
                  var cwidth = MediaQuery.of(context).size.width;
                  var cheight = cwidth / 4 * 3;
                  return Stack(
                    alignment: Alignment.center,
                    // fit: StackFit.expand,
                    clipBehavior: Clip.none,
                    children: [
                      Positioned(
                        top: 0,
                        child: Container(
                          width: cwidth,
                          height: cheight,
                          color: Colors.amber,
                          child: content,
                        ),
                      ),
                      Positioned(
                        top: cheight,
                        child: GestureDetector(
                          onTap: () {
                            // 切换图片路径
                            _switchImage(
                              '/data/user/0/com.example.pro_image_editor_demo/cache/rotated_1754631300955.jpg',
                            );
                          },
                          child: Container(
                            width: cwidth,
                            height: 80,
                            color: Colors.red,
                            child: _isSwitching
                                ? Center(
                                    child: CircularProgressIndicator(
                                      color: Colors.white,
                                    ),
                                  )
                                : Center(
                                    child: Text(
                                      "切换图片",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
                appBar: (editor, rebuildStream) => ReactiveAppbar(
                  stream: rebuildStream,
                  builder: (_) => _buildAppBar(editor),
                ),
                bottomBar: (editor, rebuildStream, key) => ReactiveWidget(
                  stream: rebuildStream,
                  builder: (_) =>
                      _bottomNavigationBar(editor, key, constraints),
                ),
              ),
            ),
            filterEditor: // 在FilterEditor配置中设置
            FilterEditorConfigs(
              filterList: [
                // 无滤镜选项
                FilterModel(name: '无', filters: []),

                // 自定义滤镜
                FilterModel(
                  name: '明暗',
                  filters: [
                    ColorFilterAddons.colorOverlay(255, 225, 80, 0.08),
                    ColorFilterAddons.saturation(0.1),
                    ColorFilterAddons.contrast(0.05),
                  ],
                ),
                FilterModel(
                  name: '鲜明',
                  filters: [
                    ColorFilterAddons.grayscale(),
                    ColorFilterAddons.colorOverlay(100, 28, 210, 0.03),
                    ColorFilterAddons.brightness(0.1),
                  ],
                ),
                FilterModel(
                  name: '对比',
                  filters: [
                    ColorFilterAddons.addictiveColor(0, 0, 20),
                  ],
                ),
              ],
              widgets: FilterEditorWidgets(
                  bottomBar: (state, rebuildStream) => ReactiveWidget(builder: (context){
                    return CustomFilterBottomBar(state: state);
                  }, stream: rebuildStream)
              ),
            ),
            tuneEditor: TuneEditorConfigs(widgets: TuneEditorWidgets()),
          ),
        );
      },
    );
  }

  AppBar _buildAppBar(ProImageEditorState editor) {
    print("_buildAppBar editor: $editor");
    return AppBar(
      title: Text("预览照片", style: TextStyle(color: Colors.white)),
      centerTitle: true,
      automaticallyImplyLeading: false,
      leading: IconButton(
        tooltip: 'Cancel',
        padding: const EdgeInsets.symmetric(horizontal: 8),
        icon: const Icon(Icons.close),
        onPressed: editor.closeEditor,
      ),
      foregroundColor: Colors.white,
      backgroundColor: Colors.black,
      actions: [
        IconButton(
          tooltip: 'Undo',
          padding: const EdgeInsets.symmetric(horizontal: 8),
          icon: Icon(
            Icons.undo,
            color: editor.canUndo == true
                ? Colors.white
                : Colors.white.withAlpha(80),
          ),
          onPressed: editor.undoAction,
        ),
        IconButton(
          tooltip: 'Redo',
          padding: const EdgeInsets.symmetric(horizontal: 8),
          icon: Icon(
            Icons.redo,
            color: editor.canRedo == true
                ? Colors.white
                : Colors.white.withAlpha(80),
          ),
          onPressed: editor.redoAction,
        ),
        IconButton(
          tooltip: 'Done',
          padding: const EdgeInsets.symmetric(horizontal: 8),
          icon: const Icon(Icons.done),
          iconSize: 28,
          onPressed: editor.doneEditing,
        ),
      ],
    );
  }

  AppBar _appBarFilterEditor(FilterEditorState filterEditor) {
    return AppBar(
      automaticallyImplyLeading: false,
      backgroundColor: Colors.black,
      foregroundColor: Colors.white,
      leading: IconButton(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        icon: const Icon(Icons.arrow_back),
        onPressed: filterEditor.close,
      ),
      title: Text("美化", style: TextStyle(color: Colors.white)),
      centerTitle: true,
    );
  }

  Widget _bottomNavigationBar(
    ProImageEditorState editor,
    Key key,
    BoxConstraints constraints,
  ) {
    return Scrollbar(
      /// Key is important for correct layer calculations
      key: key,
      controller: _bottomBarScrollCtrl,
      scrollbarOrientation: ScrollbarOrientation.top,
      thickness: isDesktop ? null : 0,
      child: BottomAppBar(
        height: kBottomNavigationBarHeight,
        color: Colors.black,
        padding: EdgeInsets.zero,
        child: Center(
          child: SingleChildScrollView(
            controller: _bottomBarScrollCtrl,
            scrollDirection: Axis.horizontal,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minWidth: min(constraints.maxWidth, 500),
                maxWidth: 500,
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    FlatIconTextButton(
                      label: Text('删除', style: _bottomTextStyle),
                      icon: const Icon(
                        Icons.edit_rounded,
                        size: 22.0,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        editor.closeEditor();
                      },
                    ),
                    FlatIconTextButton(
                      label: Text(
                        '马赛克',
                        style: _bottomTextStyle.copyWith(color: Colors.amber),
                      ),
                      icon: const Icon(
                        Icons.new_releases_outlined,
                        size: 22.0,
                        color: Colors.amber,
                      ),
                      onPressed: editor.openPaintEditor,
                    ),
                    FlatIconTextButton(
                      label: Text('美化', style: _bottomTextStyle),
                      icon: const Icon(
                        Icons.filter,
                        size: 22.0,
                        color: Colors.white,
                      ),
                      onPressed: editor.openFilterEditor,
                    ),
                    FlatIconTextButton(
                      label: Text('调节', style: _bottomTextStyle),
                      icon: const Icon(
                        Icons.tune,
                        size: 22.0,
                        color: Colors.white,
                      ),
                      onPressed: editor.openTuneEditor,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  openPaintEditorAndBlur(editor) {
    editor.openPaintEditor();
  }
}
